#include "ws.assembler.h"
#include "ws.token.h"
#include "ws.packer.h"

#ifdef DEBUG
#include <iostream>
#endif

TOB::WS::Assembler* TOB::WS::Assembler::_self = NULL;

TOB::WS::Assembler::Assembler() {
#ifdef DEBUG
  std::cout << "Created assembler: " << this << std::endl;
#endif
}

TOB::WS::Assembler* TOB::WS::Assembler::getInstance() {
  if (_self == NULL) {
    _self = new Assembler();
  }
  return _self;
}

TOB::WS::Packer* TOB::WS::Assembler::operator [](int token) {
  if (_buffer.find(token) == _buffer.end()) {
    return NULL;
  }
  return _buffer[token];
}

void TOB::WS::Assembler::setLinkPackerByToken(TOB::WS::Packer* packer, int token) {
  _buffer[token] = packer;
}

int TOB::WS::Assembler::newPacker() {
  TOB::WS::Token* token = TOB::WS::Token::getInstance();
  
  int t = token->getToken();
  if (t == -1 || _buffer.find(t) != _buffer.end()) {
    return -1;
  }
  _buffer[t] = new TOB::WS::Packer();
  return t;
}

bool TOB::WS::Assembler::existPacker(int token) {
  return _buffer.find(token) != _buffer.end();
}

void TOB::WS::Assembler::erase(std::map<int, TOB::WS::Packer*>::iterator it) {
  _buffer.erase(it);
}

std::map<int, TOB::WS::Packer*>::iterator TOB::WS::Assembler::find(int token) {
  return _buffer.find(token);
}
